% fileretrieve.erl
%
% Handles retrieving file fragments using gossip
%
-module(fileretrieve).
-export([start/3]).
-import(erlang, [display/1]).

% start function used to do gossip
start(Neighbors, Tag, Proc) ->
	random:seed(now()),
	% iterates for number of steps
	TotalIter = ceiling(math:log(length(Neighbors)))+10,
	gFileRetrieve_helper(Neighbors, Tag, Proc, 0, TotalIter),
	ok.

% main gossip loop, at each step it gets a new node and checks if it has the fragment
gFileRetrieve_helper(Neighbors, Tag, Proc, Created, TotalIter) when TotalIter+1 == Created ->
	ok;
gFileRetrieve_helper(Neighbors, Tag, Proc, Created, TotalIter) ->
	case gossipprob:getGossipNode(Neighbors) of
	  {ok, Node} ->
			Node ! {retrieve, Tag, Proc};
		{error, _Msg} -> ok
	end,
	gFileRetrieve_helper(Neighbors, Tag, Proc, Created+1, TotalIter).

% floor and ceiling functions
floor(X) ->
    T = erlang:trunc(X),
    case (X - T) of
        Neg when Neg < 0 -> T - 1;
        Pos when Pos > 0 -> T;
        _ -> T
    end.

ceiling(X) ->
    T = erlang:trunc(X),
    case (X - T) of
        Neg when Neg < 0 -> T;
        Pos when Pos > 0 -> T + 1;
        _ -> T
    end.
